package com.livvy.commons.utils.image;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * Copyright livvy guo and other contributors
 * Released under the MIT license
 * <p/>
 * Created with IntelliJ IDEA.
 * User: GuoZheng
 * Date: 13-11-17
 * Time: 下午3:38
 * @author livvy
 * @version 1.0
 * @since 1.0
 */
public class AuthCode {

    /**
     * 默认的图片验证码宽度
     */
    public static final int DEFAULT_AUTH_CODE_WITH = 60;

    /**
     * 默认的图片验证码高度
     */
    public static final int DEFAULT_AUTH_CODE_HEIGHT = 20;

    /**
     * 根据参数code生成图片验证码
     * @author livvy
     * @param code 验证码字符串
     * @return BufferedImage图片验证码
     * @date 2013/11/17
     * @since  1.0
     */
    public static BufferedImage generateAuthCode (String code) {
        return generateAuthCode(code,DEFAULT_AUTH_CODE_WITH,DEFAULT_AUTH_CODE_HEIGHT);
    }

    /**
     *   根据参数code生成指定宽度和高度的图片验证码
     * @auther livvy
     * @param code 验证码字符串
     * @param width 图片宽度
     * @param height 图片高度
     * @return 指定宽度高度的BufferedImage图片验证码
     * @date 2013/11/17
     * @since 1.0
     */
    public static BufferedImage generateAuthCode (String code, int width,int height ) {
        if (width <= 0 || height <= 0) {
              throw new IllegalArgumentException("illegal width or height.");
        }
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        Random random = new Random();
        g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
        g.fillRect(0, 0, width, height);
        g.setColor(new Color(0, 0, 0));
        g.setFont(new Font("Segoui",Font.PLAIN,height-2));
        g.drawString(code,2,height-3);
        //增加干扰码
        for (int i = 0;i < 5; i++) {
            g.setColor(new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255)));
            g.drawLine(random.nextInt(width),random.nextInt(height),random.nextInt(width),random.nextInt(height));
        }
        return image;
    }
}
